package com.guslegend.component;


import com.guslegend.config.SmsConfig;
import com.guslegend.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@Slf4j
public class SmsComponent {

    /**
     * 发送地址
     */
    private static final String URL_TEMPLATE="https://gyytz.market.alicloudapi.com/sms/smsSend?mobile=%s&templateId=%s&smsSignId=%s&param=%s";

    private static final String PARAM = "**code**:%s,**minute**:10";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsConfig smsConfig;

    /**
     * 发送短信验证码
     * @param to
     * @param
     * @param value
     */
    @Async("threadPoolTaskExecutor")
    public void send(String to, String value) {
        String param = String.format(PARAM, value);
        String url = String.format(URL_TEMPLATE, to, smsConfig.getTemplateId(), smsConfig.getSmsSignId(), param);
        log.info(url);
        HttpHeaders headers = new HttpHeaders();

        headers.set("Authorization", "APPCODE " + smsConfig.getAppCode());
        HttpEntity entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        log.info("url={},body={}", url, response.getBody());

        if (response.getStatusCode().is2xxSuccessful()) {
            log.info("发送验证码成功");
        } else {
            log.error("发送验证码失败: {}", response.getBody());
        }
    }

}
